package com.dou.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.dou.dto.Constant;
import com.dou.dto.Dto;
import com.dou.dto.DtoUtil;
import com.dou.dto.RedisUtil;
import com.dou.entity.SeckillGoods;
import com.dou.entity.SeckillOrderStemp;
import com.dou.service.RPCSeckillGoodsService;
import com.dou.service.SeckillOrderStempService;
import org.springframework.beans.factory.annotation.Autowired;

@Service
public class RPCSeckillGoodsServiceImpl implements RPCSeckillGoodsService {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private SeckillOrderStempService seckillOrderTempService;
    /**
     * 执行抢购
     */
    @Override
    public Dto qiangGou(String tonken,int sId,int gId) {
        //判断用户是否登陆
        String uJson = redisUtil.getStr(tonken);
        if(uJson == null || uJson.equals("")){
            return DtoUtil.returnFail("用户未登陆","4001");
        }
        //消息发送MQ，然后中间件处理
        //seckill:lock:5
        //如果加锁成功开始处理
        //如果加锁失败
        //加锁执行效率变慢 每次需要等待
        //消息队列加速效率 ActiveMQ
        while (redisUtil.lock(Constant.Seckill.SECKILL_LOCK+gId,30L)){
            try {
                //休眠当前线程
                Thread.sleep(30);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
        //是否有库存
        String gJson = redisUtil.getStr(Constant.Seckill.SECKILL_GOODS+sId+":"+gId);
        if (gJson == null || uJson.equals("")){
            redisUtil.unlock(Constant.Seckill.SECKILL_LOCK+gId);
            return DtoUtil.returnFail("找不到对应商品","4002");
        }
        SeckillGoods goods = JSONObject.toJavaObject(JSONObject.parseObject(gJson),SeckillGoods.class);
        if(goods.getSstock()<1){
            return DtoUtil.returnSuccess("库存不足");
        }
        //查询用户是否购买 查询订单表？订单表中有其他数据，查询不便，创建临时表存储
        SeckillOrderStemp sot = new SeckillOrderStemp();
        sot.setUid(Integer.valueOf(JSONObject.parseObject(uJson).getString("id")));
        sot.setSid(sId);
        sot.setGid(gId);
        int count = seckillOrderTempService.getCount(sot);
        if(count != 0){
            return DtoUtil.returnSuccess("只能购买一次");
        }
        //开始抢购
        //修改库存
        int sstock=goods.getSstock();
        System.out.println(sstock);
        goods.setSstock(sstock-1);
        redisUtil.setStr(Constant.Seckill.SECKILL_GOODS+":"+gId,JSONObject.toJSONString(goods));
        //新增秒杀临时表中记录
        sot.setStatus(0);
        seckillOrderTempService.insert(sot);
        //创建订单
        redisUtil.unlock(Constant.Seckill.SECKILL_LOCK + gId);
        return DtoUtil.returnSuccess("抢购成功");
    }
}
